const { json } = require("body-parser");
const express = require("express");
const router = express.Router();
const passport = require("passport");

const Profile = require("../../models/Profile");

router.get("/test", (req, res) => {
  res.json({ msg: "profile" })
})

// post  api/profile/add
// 添加文章接口
router.post("/add", passport.authenticate("jwt", { session: false }), (req, res) => {
  const content = {};
  content.title = req.body.title;
  content.article = req.body.article;
  new Profile(content).save().then(profile => {
    res.json({
      status: 200,
      data: "添加成功"
    });
  }).catch(err => {
    res.json({
      status: 500,
      data: "添加失败,原因:" + err
    });
  });
});

// get  api/profile
// 获取所有内容
router.get("/", (req, res) => {
  Profile.find().then(profile => {
    if (!profile) {
      return res.json({
        status: 404,
        data: "内容为空"
      });
    }
    res.json({
      status: 200,
      data: profile
    });
  }).catch(err => res.json({
    status: 500,
    data: "获取失败,原因:" + err
  }));
});

// get  api/profile/:id
// 获取单个内容
router.get("/:id", passport.authenticate("jwt", { session: false }), (req, res) => {
  Profile.findOne({
    _id: req.params.id
  }).then(profile => {
    if (!profile) {
      return res.json({
        status: 404,
        data: "暂无内容"
      });
    }
    res.json({
      status: 200,
      data: profile
    });
  }).catch(err => res.json({
    status: 500,
    data: "获取失败,原因" + err
  }));
});

// post  api/profile/edit
// 编辑文章接口
router.post("/edit/:id", passport.authenticate("jwt", { session: false }), (req, res) => {
  const content = {};
  content.article = req.body.article;
  Profile.findOneAndUpdate(
    { _id: req.params.id, },
    { $set: content },
    { new: true }
  ).then(profile => {
    res.json({
      status: 200,
      data: "修改成功"
    });
  }).catch(err => res.json({
    status: 500,
    data: "修改失败，原因:" + err
  }));
});

// post  api/profile/delete/:id
// 删除文章接口
router.delete('/delete/:id', (req, res) => {
  Profile.findOneAndRemove({ _id: req.params.id }).then(profile => {
    res.json({
      status: 200,
      data: "删除成功"
    });
  }).catch(err => {
    res.json({
      status: 500,
      data: "删除失败,原因:" + err
    });
  });
});

module.exports = router;